{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9c1328a6",
   "metadata": {},
   "source": [
    "基于字典的文本情感分析方案"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84270a09",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch  \n",
    "import torch.nn as nn  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f3462d9-36ba-45f0-b643-276cfc642292",
   "metadata": {},
   "outputs": [],
   "source": [
    "sentiment_dict = {  \n",
    "    \"good\": 1,  \n",
    "    \"bad\": -1,  \n",
    "    \"happy\": 1,  \n",
    "    \"sad\": -1,  \n",
    "    # ... 更多词汇  \n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca123480-a4c6-492a-8f0b-b42590b3ac2e",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "class SentimentAnalyzer(nn.Module):  \n",
    "    def __init__(self, sentiment_dict):  \n",
    "        super(SentimentAnalyzer, self).__init__()  \n",
    "        self.sentiment_dict = sentiment_dict  \n",
    "  \n",
    "    def forward(self, text):  \n",
    "        # 将文本转换为小写并分割  \n",
    "        words = text.lower().split()  \n",
    "          \n",
    "        # 计算情感得分  \n",
    "        scores = [self.sentiment_dict.get(word, 0) for word in words]  \n",
    "          \n",
    "        # 如果所有单词都不在词典中，返回0  \n",
    "        if all(score == 0 for score in scores):  \n",
    "            return torch.tensor(0.0)  \n",
    "  \n",
    "        # 计算平均情感得分  \n",
    "        avg_score = sum(scores) / len(scores)  \n",
    "        return torch.tensor(avg_score)  \n",
    "  \n",
    "# 示例使用  \n",
    "sentiment_dict = {  \n",
    "    \"good\": 1,  \n",
    "    \"bad\": -1,  \n",
    "    \"happy\": 1,  \n",
    "    \"sad\": -1,  \n",
    "}  \n",
    "  \n",
    "analyzer = SentimentAnalyzer(sentiment_dict)  \n",
    "text = \"I am happy but also sad\"  \n",
    "score = analyzer(text)  \n",
    "print(f\"Sentiment score for '{text}': {score.item()}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
